package com.autumn.sms.service.services.impl;

import java.util.Date;
import java.util.concurrent.atomic.AtomicBoolean;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Service;

import com.autumn.sms.service.entities.mongodb.SendFailData;
import com.autumn.sms.service.entities.mongodb.SendSuccessData;
import com.autumn.sms.service.services.ISendLogService;
import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;

/**
 * 发送日志服务实现
 * 
 * @author 老码农
 *
 *         2018-01-13 18:26:33
 */
@Service
public class SendLogServiceImpl implements ISendLogService {

	@Autowired
	private MongoTemplate template;
	private AtomicBoolean isCreateFailData = new AtomicBoolean(false);
	private AtomicBoolean isSuccessData = new AtomicBoolean(false);

	private boolean isInitialize(AtomicBoolean atom, String name) {
		boolean isInit = false;
		if (!atom.get()) {
			if (!template.collectionExists(name)) {
				isInit = true;
			}
			atom.set(true);
		}
		return isInit;
	}

	private void createCommonIndex(DBCollection db) {
		db.createIndex("sendTime");
		db.createIndex("messageId");
		db.createIndex("mobilePhone");
		db.createIndex("serviceId");
		db.createIndex("serviceAddress");
		db.createIndex("clientIp");
	}

	@Override
	public void saveFail(SendFailData data) {
		boolean isInit = isInitialize(isCreateFailData, SendFailData.COLLECTION_NAME);
		data.setSendTime(new Date());
		template.insert(data, SendFailData.COLLECTION_NAME);
		if (isInit) {
			DBCollection db = template.getCollection(SendFailData.COLLECTION_NAME);
			createCommonIndex(db);
			db.createIndex(new BasicDBObject("errorMessage", "text"));
		}
	}

	@Override
	public void saveSuccess(SendSuccessData data) {
		boolean isInit = isInitialize(isSuccessData, SendSuccessData.COLLECTION_NAME);
		data.setSendTime(new Date());
		template.insert(data, SendSuccessData.COLLECTION_NAME);
		if (isInit) {
			DBCollection db = template.getCollection(SendSuccessData.COLLECTION_NAME);
			createCommonIndex(db);
		}
	}

}
